package com.geeka.d12.work.chatroom;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpClientDemo1ChatRoom {
    public static void main(String[] args) {

        try{
            //1, 建立连接
            Socket socket = new Socket("127.0.0.1", 9999);

            // 输出流
            OutputStream ops = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ops));
//            PrintWriter pw = new PrintWriter(ops);
            Scanner scan = new Scanner(System.in);
            // 向服务器发送消息的线程
            OutPutThread outPutThread = new OutPutThread(scan, bw, socket);
            Thread t1 = new Thread(outPutThread);
            t1.start();


            // 输入流
            InputStreamReader ips = new InputStreamReader(socket.getInputStream());
            BufferedReader br = new BufferedReader(ips);
            String s = null;
            // 接收服务器消息的线程
            InputThread inputThread = new InputThread( br);
            Thread t2 = new Thread(inputThread);
            t2.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 输出线程
class OutPutThread implements Runnable {
    public Scanner scan;
//    public PrintWriter pw;
    public Socket socket;
    public BufferedWriter bw;

    public OutPutThread(Scanner scan, BufferedWriter bw, Socket socket) {
        this.scan = scan;
//        this.pw = pw;
        this.bw = bw;
        this.socket = socket;
    }

    @Override
    public void run() {
//        System.out.println("I'm going to start to run");
        while (true) {
            System.out.println("请输入信息:  ");
            String next = scan.next();
            try {
                bw.write(next); // 输出到服务端
                bw.newLine();
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

// 输入线程
class InputThread implements Runnable {

    private String s = null;
    private BufferedReader br;
    public InputThread(BufferedReader br) {

        this.br = br;
    }

    @Override
    public void run() {

        while (true) {
            try {
                if ((s = br.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}